package com.easychat.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.easychat.entity.dto.MessageSendDto;
import com.easychat.entity.dto.SysSettingDto;
import com.easychat.entity.dto.UserContactSearchResultDto;
import com.easychat.entity.enums.*;
import com.easychat.entity.po.*;
import com.easychat.entity.query.*;
import com.easychat.entity.vo.PaginationResultVO;
import com.easychat.exception.BusinessException;
import com.easychat.mappers.*;
import com.easychat.redis.RedisComponent;
import com.easychat.service.UserContactService;
import com.easychat.utils.CopyTools;
import com.easychat.utils.StringTools;
import com.easychat.websocket.netty.ChannelContextUtils;
import com.easychat.websocket.netty.MessageHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 联系人 业务接口实现
 */
@Service("userContactService")
public class UserContactServiceImpl implements UserContactService {

    @Resource
    private UserContactMapper<UserContact, UserContactQuery> userContactMapper;
    @Resource
    private UserInfoMapper<UserInfo, UserInfoQuery> userInfoMapper;
    @Resource
    private GroupInfoMapper<GroupInfo, GroupInfoQuery> groupInfoMapper;
    @Resource
    private RedisComponent redisComponent;

    @Resource
    private ChatSessionMapper<ChatSession, ChatSessionQuery> chatSessionMapper;
    @Resource
    private ChatSessionUserMapper<ChatSessionUser, ChatSessionUserQuery> chatSessionUserMapper;
    @Resource
    private ChatMessageMapper<ChatMessage, ChatMessageQuery> chatMessageMapper;
    @Resource
    private MessageHandler messageHandler;


    @Resource
    private ChannelContextUtils channelContextUtils;


    public static Logger logger = LoggerFactory.getLogger(UserContactServiceImpl.class);

    /**
     * 根据条件查询列表
     */
    @Override
    public List<UserContact> findListByParam(UserContactQuery param) {
        return this.userContactMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(UserContactQuery param) {
        return this.userContactMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<UserContact> findListByPage(UserContactQuery param) {
        int count = this.findCountByParam(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<UserContact> list = this.findListByParam(param);
        PaginationResultVO<UserContact> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(UserContact bean) {
        return this.userContactMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<UserContact> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userContactMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<UserContact> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userContactMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 多条件更新
     */
    @Override
    public Integer updateByParam(UserContact bean, UserContactQuery param) {
        StringTools.checkParam(param);
        return this.userContactMapper.updateByParam(bean, param);
    }

    /**
     * 多条件删除
     */
    @Override
    public Integer deleteByParam(UserContactQuery param) {
        StringTools.checkParam(param);
        return this.userContactMapper.deleteByParam(param);
    }

    /**
     * 根据UserIdAndContactId获取对象
     */
    @Override
    public UserContact getUserContactByUserIdAndContactId(String userId, String contactId) {
        return this.userContactMapper.selectByUserIdAndContactId(userId, contactId);
    }

    /**
     * 根据UserIdAndContactId修改
     */
    @Override
    public Integer updateUserContactByUserIdAndContactId(UserContact bean, String userId, String contactId) {
        return this.userContactMapper.updateByUserIdAndContactId(bean, userId, contactId);
    }

    /**
     * 根据UserIdAndContactId删除
     */
    @Override
    public Integer deleteUserContactByUserIdAndContactId(String userId, String contactId) {
        return this.userContactMapper.deleteByUserIdAndContactId(userId, contactId);
    }

    @Override
    public UserContactSearchResultDto searchContact(String userId, String contactId) {


        //1.判断搜的是群组还是用户
        UserContactTypeEnum typeEnum = UserContactTypeEnum.getByPrefix(contactId.substring(0, 1));
        if (typeEnum == null) {
            return null;
        }
        UserContactSearchResultDto resultDto = new UserContactSearchResultDto();
        switch (typeEnum) {
            case USER:
                //是用户
                UserInfo userInfo = userInfoMapper.selectByUserId(contactId);
                if (userInfo == null) {
                    return null;
                }
                BeanUtils.copyProperties(userInfo, resultDto);
                resultDto.setContactId(userInfo.getUserId());
                break;
            case GROUP:
                //是群组
                GroupInfo groupInfo = groupInfoMapper.selectByGroupId(contactId);
                if (groupInfo == null) {
                    return null;
                }
                resultDto.setNickName(groupInfo.getGroupName());
                break;
        }
        resultDto.setContactType(typeEnum.toString());
        resultDto.setContactId(contactId);
        //搜索自己
        if (contactId.equals(userId)) {
            resultDto.setStatus(UserContactStatusEnum.FRIEND.getCode());
            return resultDto;
        }
        //2.判断是否是好友，设置 联系人状态
        UserContact userContact = userContactMapper.selectByUserIdAndContactId(userId, contactId);
        resultDto.setStatus(userContact == null ? null : userContact.getStatus());//非好友 :null  好友：


        return resultDto;
    }

    @Transactional
    @Override
    public void delContact(String userId, String contactId, UserContactStatusEnum statusEnum) {
        //删除好友只是更新状态，并不是在数据库中删除

        //更新我的状态
        UserContact userContact = new UserContact();
        userContact.setStatus(statusEnum.getCode());
        userContactMapper.updateByUserIdAndContactId(userContact, userId, contactId);

        //更新对方看我的状态
        UserContact friendContact = new UserContact();
        if (statusEnum.equals(UserContactStatusEnum.DELETE)) {
            friendContact.setStatus(UserContactStatusEnum.DELETE_BE.getCode());
        } else if (statusEnum.equals(UserContactStatusEnum.BLACK)) {
            friendContact.setStatus(UserContactStatusEnum.BLACK_BE.getCode());
        }
        userContactMapper.updateByUserIdAndContactId(friendContact, contactId, userId);
        // 从对方的好友列表缓存中删除
        redisComponent.removeUserContact(userId,contactId);
        // 从我的好友列表缓存中删除
        redisComponent.removeUserContact(contactId,userId);

    }

    @Override
    public void addContact(String applyUserId, String receiveUserId, String contactId, Integer contactType, String applyInfo) {
        //校验：检查群是否满人
        if (UserContactTypeEnum.GROUP.getType().equals(contactType)) {
            UserContactQuery userContactQuery = new UserContactQuery();
            userContactQuery.setContactId(contactId);
            userContactQuery.setContactType(UserContactTypeEnum.GROUP.getType());
            Integer count = userContactMapper.selectCount(userContactQuery);
            logger.info("该群人数count:{}", count);
            SysSettingDto sysSettingDto = redisComponent.getSysSettingDto();
            Integer maxGroupMemberCount = sysSettingDto.getMaxGroupMemberCount();
            logger.info("系统设置最大群人数maxGroupMemberCount:{}", maxGroupMemberCount);
            if (count >= maxGroupMemberCount) {
                throw new BusinessException("该群已经满员");
            }
        }
        Date curDate = new Date();
        List<UserContact> userContactList = new ArrayList<>();
        //抽取共同的1条记录
        UserContact userContact = new UserContact();
        userContact.setUserId(applyUserId);
        userContact.setContactId(contactId);
        userContact.setContactType(contactType);
        userContact.setStatus(UserContactStatusEnum.FRIEND.getCode());
        userContact.setLastUpdateTime(curDate);
        userContact.setCreateTime(curDate);
        userContactList.add(userContact);

        //如果是好友，添加一条记录
        if (UserContactTypeEnum.USER.getType().equals(contactType)) {
            UserContact userContact2 = new UserContact();
            userContact2.setUserId(receiveUserId);
            userContact2.setContactId(applyUserId);
            userContact2.setContactType(contactType);
            userContact2.setStatus(UserContactStatusEnum.FRIEND.getCode());
            userContact2.setLastUpdateTime(curDate);
            userContact2.setCreateTime(curDate);
            userContactList.add(userContact2);
        }

        //批量插入
        userContactMapper.insertOrUpdateBatch(userContactList);
        logger.info("添加联系人成功");

        // 添加好友后，将联系人存储到缓存
        if (UserContactTypeEnum.USER.getType().equals(contactType)) {
            //如果是好友，要互相添加记录
            redisComponent.addUserContact(receiveUserId, applyUserId);
        }
        redisComponent.addUserContact(applyUserId, contactId);

        // 创建会话

        //获取sessionId
        String sessionId = null;
        if (contactType.equals(UserContactTypeEnum.USER.getType())) {
            //如果是好友，创建会话
            sessionId = StringTools.getChatSessionIdUser(new String[]{applyUserId, contactId});
        } else if (contactType.equals(UserContactTypeEnum.GROUP.getType())) {
            //如果是群，创建会话
            sessionId = StringTools.getChatSessionIdGroup(contactId);
        }

        /**
         * 用户+用户，添加成功后创建会话发送消息
         * chat session user   添加2条记录
         * chat session 添加1条记录
         *  chat message 添加1条记录
         */
        List<ChatSessionUser> chatSessionUserList = new ArrayList<>();
        if (contactType.equals(UserContactTypeEnum.USER.getType())) {
            //chat session
            ChatSession chatSession = new ChatSession();
            chatSession.setLastMessage(applyInfo);
            chatSession.setSessionId(sessionId);
            chatSession.setLastReceiveTime(curDate.getTime());
            chatSessionMapper.insertOrUpdate(chatSession);
            // chat session user    申请人
            ChatSessionUser applyChatSessionUser = new ChatSessionUser();
            applyChatSessionUser.setUserId(applyUserId);
            applyChatSessionUser.setContactId(contactId);
            applyChatSessionUser.setSessionId(sessionId);
            UserInfo contactUser = userInfoMapper.selectByUserId(contactId);
            applyChatSessionUser.setContactName(contactUser.getNickName());
            chatSessionUserList.add(applyChatSessionUser);
            // chat session user    接收人
            ChatSessionUser receiveChatSessionUser = new ChatSessionUser();
            receiveChatSessionUser.setUserId(contactId);
            receiveChatSessionUser.setContactId(applyUserId);
            receiveChatSessionUser.setSessionId(sessionId);
            UserInfo applyUser = userInfoMapper.selectByUserId(applyUserId);
            receiveChatSessionUser.setContactName(applyUser.getNickName());
            chatSessionUserList.add(receiveChatSessionUser);

            chatSessionUserMapper.insertOrUpdateBatch(chatSessionUserList);
            // chat message
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setSessionId(sessionId);
            chatMessage.setMessageType(MessageTypeEnum. ADD_FRIEND.getType());
            chatMessage.setMessageContent(applyInfo);
            chatMessage.setSendUserId(applyUserId);
            chatMessage.setSendUserNickName(applyUser.getNickName());
            chatMessage.setSendTime(curDate.getTime());
            chatMessage.setContactId(contactId);
            chatMessage.setContactType(UserContactTypeEnum.USER.getType());
            chatMessageMapper.insert(chatMessage);

            MessageSendDto messageSendDto = new MessageSendDto();
            BeanUtils.copyProperties(chatMessage, messageSendDto);
            //发送给 接受好友申请的人
            messageHandler.sendMessage(messageSendDto);
            //发送给 申请人：对于申请人来说，contact id 是接受申请的人
            messageSendDto.setMessageType(MessageTypeEnum.ADD_FRIEND_SELF.getType());
            messageSendDto.setContactId(applyUserId);
            messageSendDto.setExtendData(contactUser);
            messageHandler.sendMessage(messageSendDto);

        }else {
            //加入群组
            ChatSessionUser chatSessionUser = new ChatSessionUser();
            chatSessionUser.setUserId(applyUserId);
            chatSessionUser.setContactId(contactId);
            GroupInfo groupInfo = this.groupInfoMapper.selectByGroupId(contactId);
            chatSessionUser.setContactName(groupInfo.getGroupName());
            chatSessionUser.setSessionId(sessionId);
            this.chatSessionUserMapper.insertOrUpdate(chatSessionUser);
            //将群组加入到用户的联系人列表
            redisComponent.addUserContact(applyUserId, groupInfo.getGroupId());

            channelContextUtils.addUser2Group(applyUserId, groupInfo.getGroupId());


            UserInfo applyUserInfo = this.userInfoMapper.selectByUserId(applyUserId);
            String sendMessage = String.format(MessageTypeEnum.ADD_GROUP.getInitMessage(), applyUserInfo.getNickName());
            //chat session
            ChatSession chatSession = new ChatSession();
            chatSession.setSessionId(sessionId);
            chatSession.setLastReceiveTime(curDate.getTime());
            chatSession.setLastMessage(sendMessage);
            this.chatSessionMapper.insertOrUpdate(chatSession);

            //chat message
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setSessionId(sessionId);
            chatMessage.setMessageType(MessageTypeEnum.ADD_GROUP.getType());
            chatMessage.setMessageContent(sendMessage);
            chatMessage.setSendUserId(null);
            chatMessage.setSendUserNickName(null);
            chatMessage.setSendTime(curDate.getTime());
            chatMessage.setContactId(contactId);
            chatMessage.setContactType(UserContactTypeEnum.GROUP.getType());
            chatMessage.setStatus(MessageStatusEnum.SENDED.getStatus());
            chatMessageMapper.insert(chatMessage);

            //发送群消息
            MessageSendDto messageSend = CopyTools.copy(chatMessage, MessageSendDto.class);
            messageSend.setContactId(groupInfo.getGroupId());
                 //获取群人数
            UserContactQuery userContactQuery = new UserContactQuery();
            userContactQuery.setContactId(contactId);
            userContactQuery.setStatus(UserContactStatusEnum.FRIEND.getCode());
            Integer memberCount = this.userContactMapper.selectCount(userContactQuery);
            messageSend.setMemberCount(memberCount);
            messageSend.setContactName(groupInfo.getGroupName());
            messageHandler.sendMessage(messageSend);
        }


    }

    //添加机器人好友
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addContactRobot(String userId) {
        Date curDate = new Date();
        SysSettingDto sysSettingDto = redisComponent.getSysSettingDto();
        String robotUid = sysSettingDto.getRobotUid();
        String robotNickName = sysSettingDto.getRobotNickName();
        String sendMessage = sysSettingDto.getRobotWelcome();
        sendMessage = StringTools.cleanHtmlTag(sendMessage);//过滤html标签

        //添加机器人为好友 userContact
        UserContact userContact = new UserContact();
        userContact.setUserId(userId);
        userContact.setContactId(robotUid);
        userContact.setContactType(UserContactTypeEnum.USER.getType());
        userContact.setCreateTime(curDate);
        userContact.setLastUpdateTime(curDate);
        userContact.setStatus(UserContactStatusEnum.FRIEND.getCode());
        userContactMapper.insert(userContact);
        //增加会话信息 chat_session
        String sessionId = StringTools.getChatSessionIdUser(new String[]{userId, robotUid});//生成会话id
        ChatSession chatSession = new ChatSession();
        chatSession.setSessionId(sessionId);
        chatSession.setLastMessage(sendMessage);
        chatSession.setLastReceiveTime(curDate.getTime());
        chatSessionMapper.insert(chatSession);

        //增加会话人信息 chat_session_user
        ChatSessionUser chatSessionUser = new ChatSessionUser();
        chatSessionUser.setUserId(userId);
        chatSessionUser.setContactId(robotUid);
        chatSessionUser.setSessionId(sessionId);
        chatSessionUser.setContactName(robotNickName);
        chatSessionUserMapper.insert(chatSessionUser);

        //增加聊天消息 chat_message
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSessionId(sessionId);
        chatMessage.setSendUserId(robotUid);
        chatMessage.setContactId(userId);
        chatMessage.setContactType(UserContactTypeEnum.USER.getType());
        chatMessage.setMessageContent(sendMessage);
        chatMessage.setMessageType(MessageTypeEnum.CHAT.getType());
        chatMessage.setStatus(MessageStatusEnum.SENDED.getStatus());
        chatMessage.setSendUserNickName(robotNickName);
        chatMessage.setSendTime(curDate.getTime());

        chatMessageMapper.insert(chatMessage);

    }
}